<script setup>
// script 中的代码
import {onBeforeUnmount, onMounted, ref} from 'vue'

/**
 * 显示实时时间
 */

const nowDate = ref('')
const nowTime = ref('')
/**
 * 将小于10的数字前面补0
 * @function
 * @param {number} value
 * @returns {string} 返回补0后的字符串
 */
const complement = (date) => {
  return date < 10 ? `0${date}` : date.toString()
}
/**
 * 格式化时间为XXXX年XX月XX日XX时XX分XX秒
 * @function
 * @returns {string} 返回格式化后的时间
 */
const formatDate = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = complement(date.getMonth() + 1)
  const day = complement(date.getDate())
  const week = '星期' + '日一二三四五六'.charAt(date.getDay());
  return `${year}年${month}月${day}日 ${week}`
}
const formatTime = () => {
  const date = new Date()
  return date.toTimeString().substring(0, 8)
}
let timer = 0
/**
 * 设置定时器
 */
onMounted(() => {
  nowDate.value = formatDate()
  timer = setInterval(() => {
    nowTime.value = formatTime()
  }, 1000)
})
/**
 * 取消定时器
 */
onBeforeUnmount(() => {
  clearInterval(timer) //清除定时器
  timer = 0
})

defineExpose({
  nowDate,
  nowTime
})
</script>

<template>
  {{ nowDate }}
  {{ nowTime }}
</template>

<style scoped>

</style>